<template>
  <div class="page_root" :key="queryUpdateFlag" data-page-name="投入管理" data-page-identification="f_w9fx9lwoc2">
    <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
      <!-- begin vid_j9qqotobhz 自定义模板_vx1blzeaqr -->
      <a-modal :visible="state.fileVisible" centered @cancel="fileCancel" :ok-button-props="{ loading: state.fileLoading }" title="导入" :footer="null">
        <a-col :span="24">
          <a-form-item label="导入月份">
            <a-date-picker style="width: 100%" picker="month" v-model:value="state.importDate" value-format="YYYY-MM" :allow-clear="false" />
          </a-form-item>
        </a-col>
        <a-upload :multiple="true" :before-upload="handlerUpload" @remove="handlerRemove" accept=".xlsx, image/*,.docx,, .xls,.mp4">
          <a-button type="primary">
            <upload-outlined />
            上传
          </a-button>
        </a-upload>
      </a-modal>
      <a-modal :visible="state.visible" title="投入度编辑" centered @cancel="cancelModal" @ok="submitModal" width="800px" :ok-button-props="{ loading: state.okLoading }" destroy-on-close>
        <div class="modal-title">
          剩余投入度：<span class="modal-num">{{ remainingTrd }}</span>
        </div>
        <div class="form-content">
          <a-form :model="currentData.projectMonthlyUserInvestmentList" ref="completeRef">
            <div class="module-item" v-for="(item, index) in currentData.projectMonthlyUserInvestmentList" :key="index">
              <div class="form-content">
                <a-row>
                  <a-col :span="12">
                    <a-form-item
                      label="项目名称"
                      :rules="[
                                                { required: true, message: '请选择项目名称！', trigger: 'blur' },
                                                { validator: validateProjectName, trigger: 'blur' }
                                            ]"
                      :name="[index, 'projectId']"
                    >
                      <a-tree-select
                        treeDefaultExpandAll
                        v-model:value="
                                                    currentData.projectMonthlyUserInvestmentList[index].projectId
                                                "
                        show-search
                        style="width: 100%"
                        placeholder="请选择"
                        allow-clear
                        :tree-data="state.treeData"
                        tree-node-filter-prop="projectName"
                        :fieldNames="{
                                                    children: 'children',
                                                    label: 'projectName',
                                                    value: 'projectId'
                                                }"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item
                      label="投入度"
                      :labelCol="{ span: 6 }"
                      :wrapperCol="{ span: 18 }"
                      :rules="[
                                                { required: true, message: '请输入投入度！', trigger: 'blur' },
                                                { validator: validateInvestment, trigger: 'blur' }
                                            ]"
                      :name="[index, 'investment']"
                    >
                      <a-input-number
                        style="width: 100%"
                        v-model:value="
                                                    currentData.projectMonthlyUserInvestmentList[index].investment
                                                "
                        placeholder="请输入（支持两位小数）"
                        :min="0"
                        :max="1"
                        :step="0.01"
                        :precision="2"
                      />
                    </a-form-item>
                  </a-col>
                </a-row>
              </div>

              <a class="del" @click="handlerDeleteProject(index)">删除</a>
              <!--                            <a class="add-btn" @click="handlerAddFormItem1(index, '下方')">下方插入</a>-->
            </div>
            <a-button type="primary" ghost @click="handleAddProject">新增 </a-button>
          </a-form>
        </div>
      </a-modal>
      <div class="body">
        <div class="top-time">{{ state.dateStr }}</div>
        <div class="top-search">
          <a-row :gutter="24" style="height: 32px">
            <a-col :span="6" style="height: 32px">
              <a-form-item label="人员名称">
                <a-select
                  v-model:value="state.filter.userName"
                  :options="state.peopleList"
                  show-search
                  :field-names="{ label: 'label', value: 'value' }"
                  :filter-option="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                />
              </a-form-item>
            </a-col>
            <a-col :span="6" style="height: 32px">
              <a-form-item label="月份筛选">
                <a-date-picker v-model:value="state.filter.month" picker="month" value-format="YYYY-MM" style="width: 100%" :allowClear="false" />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-space size="middle">
                <a-button type="primary" @click="getData">查询</a-button>
                <a-button type="primary" ghost @click="resetData">重置</a-button>
                <a-button type="primary" @click="state.fileVisible = true">导入</a-button>
              </a-space>
            </a-col>
          </a-row>
        </div>
        <div class="content-main" v-if="state.dataSource && state.dataSource.length > 0">
          <a-row :gutter="24">
            <a-col v-for="(item, index) in state.dataSource" :span="12" style="margin-bottom: 24px">
              <div class="item-title">
                <div class="people-name"> {{ item.userName }} <span class="people-type"></span></div>
                <a-space size="small">
                  <a-button size="small" type="link" @click="handleEdit(item)"
                    ><template #icon><FormOutlined /></template> 编辑</a-button
                  >
                  <a-popconfirm title="确认删除吗？" @confirm="handleDelete(item)">
                    <a-button size="small" type="link" @click=""
                      ><template #icon><DeleteOutlined /></template>删除</a-button
                    >
                  </a-popconfirm>
                </a-space>
              </div>
              <div class="item-content">
                <div class="no-data-image" v-if="item.projectMonthlyUserInvestmentList.length == 0">
                  <div class="no-date-tip"> 暂无数据 </div>
                </div>
                <div class="content-item" v-for="(child, childIndex) in item.projectMonthlyUserInvestmentList">
                  <div class="content-left">
                    <div class="nut"></div>
                    <div class="left-title">{{ child.projectName }}</div>
                  </div>
                  <div class="content-right">
                    <div class="normal-font">投入度：</div>
                    <div class="weight-font">{{ (child.investment * 100).toFixed(2) }}%</div>
                  </div>
                </div>
              </div>
            </a-col>
          </a-row>
        </div>
        <a-empty class="empty-box" v-else />
      </div>
      <!-- end vid_j9qqotobhz 自定义模板_vx1blzeaqr -->
    </a-spin>
  </div>
</template>
<script setup lang="tsx">
  import {
      h, ref, reactive, toRaw, markRaw, watch, computed,
      onBeforeMount, onMounted, onBeforeUnmount, onUnmounted, onActivated, onDeactivated
    } from "vue";
    import { useRoute, useRouter } from 'vue-router';
    const router = useRouter();
    const route = useRoute();
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
    import { cloneDeep, localGet, merge, getDifferenceArray, traversalTreeStructure, checkCaseCondition, renderStringInTemplate, handleBreadcrumbJump, throttle, permission, getComponentParamsValue } from '@/utils/index';
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is';
    import dayjs from 'dayjs';
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart';
    import { message, notification, Modal } from 'ant-design-vue'
    import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate, parseSubFromDataList } from '@/utils/format';
    import colorTheme from '@/design/custom-theme.json';
    
    import UserTableRecords from '@/model/UserTableRecords';
    import { getAppBaseUrl } from '@/utils/index';
    import { sendToken } from "@/hooks/useIframeToken";
    import { useSystemStore } from "@/store/modules/system";
    const systemStore = useSystemStore();
    



      // 获取传入的流程ID和组件参数
      const props = defineProps({
            'processInstanceId': {
            type: [String,Number,Boolean],
            default: undefined,
        },
      })
      const immediateWatch = (source, callback) => {
        watch(source, callback, {deep: true,immediate: true })
      }



  /* -------------------------- 属性定义 -------------------------- */

      const setTimeOutList = [];
      const pageLoading = reactive({
        loading: false,
        tip: undefined
      });
      const authInfo = localGet('app-user-store');




      // 处理校验
      const setSubFormName =(parentInfo, name)=>{
        return [parentInfo.parents, parentInfo.cycleIndex, name];
      }


  /* ========================== 属性定义 ========================== */


  /* -------------------------- 元素数据引用 -------------------------- */


  /* ========================== 元素数据引用 ========================== */


  /* -------------------------- 页面数据 -------------------------- */


  /* ========================== 页面数据 ========================== */



  /* -------------------------- 响应 -------------------------- */

  /* ========================== 响应 ========================== */


  /* -------------------------- 函数 -------------------------- */

  /* ========================== 函数 ========================== */


  /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId,
    })

  /* ========================== 页面参数 ========================== */


  /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================


  /* ========================== 组件事件处理方法 ========================== */


  /* -------------------------- 生命周期 -------------------------- */
  // 用于参数变更后重新执行自定义指令
      const queryUpdateFlag = ref(0);
      onMounted(() => { ;

    });

    onUnmounted(() => {
      // 销毁定时器
      setTimeOutList.forEach(({ repeat, timer }) => {
        repeat ?  clearInterval(timer): clearTimeout(timer);
      });
    });

  /* ========================== 生命周期 ========================== */


  /* -------------------------- 数据关联处理 -------------------------- */





  /* -------------------------- 表单数据同步 -------------------------- */
  /* ========================== 表单数据同步 ========================== */

  /* ========================== 数据关联处理 ========================== */


  /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

  /* ========================== 不同组件自定义的处理逻辑 ========================== */


  // ================================定制化逻辑========================================
  onMounted(() => {
          const formattedMonth = dayjs().format('YYYY-MM')
          const lastMonth = dayjs().subtract(1, 'month')
          state.dateStr = formattedMonth
          // 格式化时间为 yyyy-mm
          state.filter.month = formattedMonth
          state.importDate = formattedMonth
          // state.filter.month = lastMonth.format('YYYY-MM')
          // state.importDate = lastMonth.format('YYYY-MM')
          getTreeData()

          getData()
      })
      const state = reactive({
          filter: {
              month: undefined,
              userName: ''
          },
          importDate: undefined,
          dateStr: undefined,
          fileVisible: false,
          fileList: [],
          dataSource: [],
          visible: false,
          fileLoading: false,
          trdTotal: 1,
          treeData: [],
          peopleList: [],
          okLoading: false
      })
      // 校验项目名称是否重复
      const validateProjectName = (rule, value, callback) => {
          // 如果 value 为空，跳过重复校验
          if (!value) {
              return Promise.resolve()
          }
          const arr = currentData.value.projectMonthlyUserInvestmentList.filter(item => item.projectId === value)
          if (arr.length > 1) {
              return Promise.reject('项目名称不能重复！')
          } else {
              return Promise.resolve()
          }
      }

      // 校验投入度是否超出
      const validateInvestment = (rule, value, callback) => {
          if (!value) {
              return Promise.resolve()
          }
          // 计算所有投入度的总和
          const totalInvestment = currentData.value.projectMonthlyUserInvestmentList.reduce(
              (sum, item) => sum + (parseFloat(item.investment) || 0),
              0
          )
          // 如果总和大于 1，返回错误
          if (totalInvestment > 1) {
              return Promise.reject('投入度总和不能大于 1')
          }
          // 如果 value 为空，跳过重复校验

          return Promise.resolve()
      }

      const currentData = ref({})
      function handleEdit(item) {
          state.visible = true
          currentData.value = cloneDeep(item)
      }
      function handleDelete(item) {
          del(
              `/solution-ppm/api/v2/built-in-system-ppm/performance_investment/user_investment?userName=${item.userName}&month=${state.filter.month}`
          ).then(data => {
              if (data.code !== 200) {
                  message.error(data.message)
                  return
              }
              message.success(data.message)
              getData()
          })
      }
      function cancelModal() {
          state.fileList = []
          state.visible = false
      }
      const projectItem = {}
      function handleAddProject() {
          if (remainingTrd.value <= 0) {
              message.error('投入度已达上限')
              return
          }
          currentData.value.projectMonthlyUserInvestmentList.push({ ...projectItem })
      }
      function handlerDeleteProject(index) {
          currentData.value.projectMonthlyUserInvestmentList.splice(index, 1)
      }
      watch(
          () => state.filter.month,
          () => {
              if (state.filter.month) {
                  const formattedDate = dayjs(state.filter.month, 'YYYY-MM').format('YYYY年MM月')
                  state.dateStr = formattedDate
              }
          },
          { deep: true }
      )
      const completeRef = ref(null)
      function submitModal() {
          completeRef.value.validate().then(valid => {
              state.okLoading = true
              if (remainingTrd.value < 0) {
                  message.error('投入度已达上限')
                  return
              }
              put('/solution-ppm/api/v2/built-in-system-ppm/performance_investment/user_investment', currentData.value)
                  .then(data => {
                      if (data.code !== 200) {
                          message.error(data.message)
                          return
                      }
                      message.success(data.message)
                      getData()
                      state.visible = false
                  })
                  .finally(() => {
                      state.okLoading = false
                  })
          })
      }
      function getData() {
          get(
              `/solution-ppm/api/v2/built-in-system-ppm/performance_investment/user_investment?userName=&month=${state.filter.month}`
          ).then(data => {
              if (data.code !== 200) {
                  message.error(data.message)
                  return
              }
              state.peopleList = data.data.map(item => {
                  return {
                      label: item.userName,
                      value: item.userName
                  }
              })
          })
          pageLoading.loading = true
          get(
              `/solution-ppm/api/v2/built-in-system-ppm/performance_investment/user_investment?userName=${state.filter.userName}&month=${state.filter.month}`
          )
              .then(data => {
                  if (data.code !== 200) {
                      message.error(data.message)
                      return
                  }
                  state.dataSource = data.data
              })
              .finally(() => {
                  pageLoading.loading = false
              })
      }
      function getTreeData() {
          get('/solution-ppm/api/v2/built-in-system-ppm/pmgf/get_all_project_tree').then(data => {
              if (data.code !== 200) {
                  message.error(data.message)
                  return
              }
              state.treeData = data.data
          })
      }
      function resetData() {
          state.filter.userName = ''
          getData()
      }
      // 计算所有 investment 值之和，确保 investment 的值有效
      const totalTrd = computed(() => {
          if (
              !currentData.value.projectMonthlyUserInvestmentList ||
              currentData.value.projectMonthlyUserInvestmentList.length === 0
          )
              return 0 // 如果 currentData 为空，直接返回 0

          return currentData.value.projectMonthlyUserInvestmentList.reduce((sum, item) => {
              const trdValue =
                  isNaN(item.investment) || item.investment === null || item.investment === undefined
                      ? 0
                      : item.investment // 过滤无效值
              return sum + Math.round(trdValue * 100) // 将 investment 转换为整数进行精确计算
          }, 0)
      })

      // 剩余投入度：最大投入度 - 当前所有 investment 值之和
      const remainingTrd = computed(() => {
          const maxTrd = 1
          const remaining = maxTrd * 100 - totalTrd.value // 使用整数计算
          return (remaining / 100).toFixed(2) // 恢复为小数并保留两位
      })
      // 父上传文件
      function handlerUpload(file) {
          const data = new FormData()
          data.append('file', file)

          post(`/solution-ppm/api/v2/built-in-system-ppm/performance_investment/import_user/${state.importDate}`, data)
              .then(data => {
                  if (data.code !== 200) {
                      message.error(data.message)
                      return
                  }
                  message.success(data.message)
                  state.fileList = []
                  state.fileVisible = false
                getData()
              })
              .catch(e => {
                  message.error('上传失败' + e)
              })

          return false
      }
      // 父移除文件
      function handlerRemove(file) {
          state.fileList = state.fileList.filter(item => item.uid !== file.uid)
      }
      function fileCancel() {
          state.fileVisible = false
      }
</script>
<style lang="less" scoped>
  .page_root {
  width: 100%;
  height: 100%;
  overflow: auto;
  }
  .page_root :deep(.@{ant-prefix}-spin-nested-loading),
  .page_root :deep(.@{ant-prefix}-spin-container)
   {
      height: 100%;
  }
  .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper)
   {
      display: flex;
      flex-flow: column nowrap;
      justify-content: flex-start;
  }
  .page_root :deep(.@{ant-prefix}-table)
   {
    flex: auto;
    overflow: auto;
  }
  .table-moreBtn_down {
    overflow: hidden; white-space: nowrap; text-overflow: ellipsis; width: 100px;
  }

  .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
    background: #ebf1ff;
  }

  /*  表格树结构样式处理，展开按钮层级增加*/
  :deep(.@{ant-prefix}-table-row-expand-icon) {
    z-index: 1;
  }
  /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
  :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 15px !important;
    width: calc(100% - 15px);
  }
  :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 30px !important;
    width: calc(100% - 30px);
  }
  :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 45px !important;
    width: calc(100% - 45px);
  }
  :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 60px !important;
    width: calc(100% - 60px);
  }

  /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
  :deep(.@{ant-prefix}-transfer-list)
   {
      height: 100%;
      width: 50%;
  }


  /*样式*/
      .body {
          background-color: #fff;
          height: 100%;
          padding: 24px;
          position: relative;
      }
      .top-time {
          font-size: 18px;
          color: #3875ff;
          font-weight: 600;
          margin-bottom: 12px;
      }
      .top-search {
          height: 32px;
          margin-bottom: 24px;
      }
      .item-title {
          height: 40px;
          background: rgba(56, 117, 255, 0.15);
          border-radius: 4px 4px 0 0;
          border-left: 4px solid #3875ff;
          display: flex;
          padding: 10px 14px 10px 14px;
          justify-content: space-between;
      }
      .item-content {
          position: relative;
          height: 180px;
          overflow-y: auto;
          background: #f5f8ff;
          padding: 8px 16px;
      }
      .no-data-image {
          width: 66px;
          height: 80px;
          background-image: url('@/assets/images/f4999963200e6893629a63a4a771ba2a.png');
          background-size: cover;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
      }
      .no-date-tip {
          font-size: 14px;
          color: #595959;
          letter-spacing: 0;
          font-weight: 400;
          margin-top: 84px;
      }
      .content-item {
          align-items: center;
          height: 33px;
          display: flex;
          justify-content: space-between;
      }
      .nut {
          height: 8px;
          width: 8px;
          background-color: #3875ff;
          border-radius: 50%;
      }
      .content-left {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
          color: #262626;
          letter-spacing: 0;
          font-weight: 400;
      }
      .content-right {
          display: flex;
      }
      .normal-font {
          font-size: 14px;
          color: #595959;
          letter-spacing: 0;
          font-weight: 400;
      }
      .weight-font {
          font-size: 14px;
          color: #262626;
          letter-spacing: 0;
          font-weight: 600;
      }
      .modal-title {
          line-height: 20px;
          padding: 10px 24px;
          height: 40px;
          background: rgba(56, 117, 255, 0.1);
          border-radius: 4px;
          margin-bottom: 16px;
      }
      .modal-num {
          font-size: 16px;
          color: #3875ff;
          letter-spacing: 0;
          text-align: right;
          font-weight: 500;
      }
      .form-content {
          display: inline-block;
          width: calc(100% - 30px);
      }
      .module-item {
          position: relative;
      }
      .del {
          width: 28px;
          color: #3875ff;
          position: absolute;
          right: -10px;
          top: 5px;
      }
      .content-main {
          height: calc(100% - 120px);
          overflow-y: auto;
          overflow-x: hidden;
          background-color: #fff;
      }
      .empty-box {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
      }
      .people-name {
          font-size: 16px;
        line-height: 20px;
          color: #262626;
          letter-spacing: 0;
          font-weight: 600;
      }
      /*样式*/
</style>